package com.flower.background.controller;

import org.junit.Test;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;


@RestController
public class UploadImageController {
//    文件上传
    @PostMapping("/upload")
    public List<String> upload(@RequestParam("file")List<MultipartFile> multipartFileList) {
        System.out.println("multipartFileList==="+multipartFileList.size());
//        文件名集合
          List<String>list=new ArrayList<>();
            try{
//                判断上传文件是否为空
                if(!multipartFileList.isEmpty()&&multipartFileList.size()>0){
////                        上传后的保存文件名
//                    Map<String,String>map=new HashMap<>();
//                    循环上传文件
                    for (MultipartFile multipartFile : multipartFileList) {

//                        获取原文件名
                        String oldFileName = multipartFile.getOriginalFilename();
//                        设置文件上传的地址目录
                        File filePath=new File("F:/graduation/static/img/flower");
//                        判断是否存在
                        if (!filePath.exists()) {
//                            不存在创建一个
                            filePath.mkdirs();
                        }
//                        设置上传的文件新名字
                        String newFileName= UUID.randomUUID().toString().replaceAll("-","").replaceAll("[a-z|A-Z]","")+
                                "_"+oldFileName;
//                        上传文件
                          multipartFile.transferTo(new File(filePath+"/"+newFileName));
//                        map.put("url","/img/flower/"+newFileName);
                        System.out.println("/img/flower/"+newFileName);
                        list.add("http://image.flower.com/img/flower/"+newFileName);
                    }

                }
                return list;
            }catch (Exception e){
                e.printStackTrace();
            }

            return  null;
    }


}
